<template>
  <nav-bar>
    <template v-slot:default>账号管理</template>
  </nav-bar>

  <van-form @submit="onSubmit" style="margin-top:50px">
    <van-field
        v-model="username"
        name="登录名"
        label="登录名"
        readonly
    />
    <van-field
        v-model="old_password"
        type="password"
        name="旧密码"
        label="旧密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
    />
    <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
    />
    <van-field
        v-model="password_confirmation"
        type="password"
        name="确认密码"
        label="确认密码"
        placeholder="确认密码"
        :rules="[{ required: true, message: '请确认密码' }]"
    />
    <div style="margin: 16px;">
      <van-button round block type="success" native-type="submit">提交</van-button>
    </div>
  </van-form>
</template>

<script>
import {reactive, toRefs, onMounted} from "vue";
import {useRouter} from "vue-router";
import {Toast} from "vant";
import {getUser, setPassword} from "network/user";
import NavBar from "components/common/navbar/NavBar";
export default {
  name: "Setting",
  components: {
    NavBar
  },
  setup() {
    const router = useRouter()

    // 数据模型
    const state = reactive({
      username: '',
      old_password: '',
      password: '',
      password_confirmation: '',
    })

    // 数据提交
    const onSubmit = () => {
      if (state.password !== state.password_confirmation) {
        return Toast.fail('两次密码不一致')
      }
      setPassword({
        old_password: state.old_password,
        password: state.password,
        password_confirmation: state.password_confirmation,
      }).then(res => {
        if (res.status === 204) {
          Toast.success('修改密码成功')
          setTimeout(() => router.back(), 1000)
        }
      })
    }

    onMounted(() => {
      getUser().then(res => state.username = res.email)
    })

    return {
      ...toRefs(state), onSubmit
    }
  }
}
</script>

<style scoped>

</style>